package cn.wolfcode.shop.service.impl;

import cn.wolfcode.shop.domain.OrderInfo;
import cn.wolfcode.shop.exception.GlobalException;
import cn.wolfcode.shop.mq.TopicSender;
import cn.wolfcode.shop.redis.RedisService;
import cn.wolfcode.shop.redis.SeckillGoodPrefixKey;
import cn.wolfcode.shop.result.CodeMsg;
import cn.wolfcode.shop.service.IOrderInfoService;
import cn.wolfcode.shop.service.ISeckillGoodService;
import cn.wolfcode.shop.service.ISeckillOrderService;
import cn.wolfcode.shop.service.ISeckillService;
import cn.wolfcode.shop.vo.GoodVo;
import cn.wolfcode.shop.service.IWebScoketService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by wolfcode-lanxw
 */
@Service
public class SeckillServiceImpl implements ISeckillService {
    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TopicSender mqSender;
    @Reference(check = false)
    private IWebScoketService webScoketService;
    @Override
    public OrderInfo doSeckill(Long userId,Long goodId) throws GlobalException {
        GoodVo goodVo = seckillGoodService.getById(goodId);
        OrderInfo order = createOrder(goodVo, userId);
        return order;
    }
    @Transactional
    public OrderInfo createOrder(GoodVo goodVo, Long userId) {
        //减库存
        int count = seckillGoodService.reduceStock(goodVo.getId());
        if(count>0){
            //下订单
            OrderInfo orderInfo = orderInfoService.createOrderInfo(goodVo,userId);
            //下秒杀订单
            seckillOrderService.createSeckillOrder(userId,goodVo.getId(),orderInfo.getOrderNo());
            return orderInfo;
        }else{
            //标记库存已经处理完毕
            throw new GlobalException(CodeMsg.STOCK_OVER);
        }

    }

    @Override
    public void syncStock(Long goodId) {
        int stock = seckillGoodService.getGoodStockById(goodId);
        if(stock>0){
            redisService.set(SeckillGoodPrefixKey.SECKILL_STOCK,goodId+"",stock);
            mqSender.sendCancelSeckillOverSignMsg(goodId);
        }
    }
}
